<?php
namespace app\common\service;

use app\common\logic\CartLogic;
use app\common\logic\GoodsLogic;
use app\mobile\Huiju\FastPay;
use app\mobile\Huiju\HuijuPay;
use app\mobile\wxpay\WeixinPay;
use think\Page;
use app\common\logic\wechat\WechatUtil;
use think\facade\Db;

class Payh5 extends Base {
    static $AUTH_CHECK = false; //默认必须登录

    public function toPay(){

        $id = input('pay_id');
        $code = input('code');
        $Fruit = 'WEIXIN_H5_PLUS';
        //支付
        Db::startTrans();
        //在线支付方式
        if($Fruit=='ALIPAY_H5' || $Fruit=='WEIXIN_H5_PLUS' || $Fruit=='UNIONPAY_H5'){
            Db::commit();
            /**
             *
            ALIPAY_H5 支付宝 H5
            WEIXIN_H5_PLUS 微信 H5 支付
            UNIONPAY_H5 银联 H5
             */
            $rsorder=M("Payment")->where(array('id'=>$id,'status'=>0))->find();
            //$openid = Db::name('social')->where('user_id',$rsorder['user_id'])->value('openid');
            //if(!$openid){
                $openid = $this->getOpenid($code);
            //}
            if(!$openid){
                $result = [
                    'status' => false,
                    'msg' => '获取用户openid失败',
                    'data' => []
                ];
                return $result;
            }
            $rsorder['openid'] = $openid;
            $rsorder['paytype'] = 'WEIXIN_XCX';
            $response = (new HuijuPay())->submitwxapp($rsorder);
            if(!$response['status']){
                $result = [
                    'status' => false,
                    'msg' => '请求支付失败，'.$response['msg'],
                    'data' => []
                ];
                return $result;
            }else{
                $result = [
                    'status' => true,
                    'msg' => '请求支付成功！',
                    'data' => [
                        'result' => $response['result'],
                    ]
                ];
                return $result;
            }

        }


        $result = [
            'status' => true,
            'msg' => '支付成功！',
            'data' => []
        ];
        return $result;
    }

    public function getOpenid($code){
        // 从“微信服务器”获取session_key和open_id
        $appid = tpcache('weixin.wx_app_appid');
        $secret = tpcache('weixin.wx_app_secret');
        if(!$appid || !$secret) {

            $result = [
                'status' => false,
                'msg' => '没有配置小程序！请联系管理员！'
            ];
            return $result;
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $re = curl_get($url);

        \think\Log::record('WxAppLogin 获取session_key', 'error');
        \think\Log::record($re, 'error');

        $re = json_decode($re, true);
        if(!is_array($re) || !isset($re['openid'])) {
            return false;
        }else{
            return $re['openid'];
        }

    }
}
